<template>
    <div>
        <van-nav-bar title="支付" left-text="返回" left-arrow @click-left="onClickLeft" />
        <div>
            <van-form @submit="onSubmit">
                <van-field v-model="fieldValue" is-link readonly label="支付方式" placeholder="请选择支付方式"
                    @click="showPicker = true" />
                <van-popup v-model:show="showPicker" round position="bottom">
                    <h3 style="font-weight: bold; font-size: 18px; color: #333; margin: 10px;">支付渠道</h3>
                    <ul style="list-style-type: none; padding: 0;">
                        <li v-for="channel in columns" :key="channel.id" 
                            :style="{
                                padding: '12px',
                                fontSize: '16px',
                                color: selectedChannel === channel.id ? '#fff' : '#555',
                                backgroundColor: selectedChannel === channel.id ? '#007bff' : '#f9f9f9',
                                borderRadius: '8px',
                                margin: '4px 0',
                                boxShadow: selectedChannel === channel.id ? '0 4px 8px rgba(0, 123, 255, 0.2)' : 'none',
                                transition: 'background-color 0.3s, box-shadow 0.3s'
                            }"
                            @click="selectChannel(channel); showWalletAmount(channel)"
                            @mouseover="hoveredChannel = channel.id"
                            @mouseleave="hoveredChannel = null">
                       
                            {{ channel.parname }}
                        </li>
                    </ul>
                    <van-button block type="primary" @click="showPicker = false">确定</van-button>
                </van-popup>

                <van-field v-model="amount" name="pattern" label="支付金额" style="width: 200px;"
                    :rules="[{ pattern, message: '请输入正确内容' }]" />
                
                <van-field v-model="selectedCount" is-link readonly label="选择优惠券" @click="showCouponList()" />
                <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
                    <div v-for="(userCouponInfo) in userCouponInfList" :key="userCouponInfo.id">
                        <div class="van-coupon-list-content">
                            <div class="van-coupon-list-head">
                                <h2 class="van-coupon-amount">
                                    <span>满 {{ userCouponInfo.couponCondition.condition }} 元</span>
                                </h2>
                                <p class="van-coupon-condition">
                                    {{ userCouponInfo.couponCondition.faceValue }}
                                </p>
                            </div>
                            <div class="van-coupon-list-body">
                                <p class="van-coupon-name">{{ userCouponInfo.coupon.name }} </p>
                                <p class="van-coupon-valid">{{ userCouponInfo.typeName }} {{ userCouponInfo.userTypeName }} {{ userCouponInfo.overlayName }}</p>
                                <van-checkbox-group v-model="checked" direction="horizontal">
                                    <van-checkbox 
                                        :name="userCouponInfo.id" 
                                        @click="checkbox(userCouponInfo.id)" 
                                        :disabled="userCouponInfo.coupon.overlay === 1 && selectedCouponIds.length > 0">
                                    </van-checkbox>
                                </van-checkbox-group>
                            </div>
                        </div>
                    </div>
                    <div style="display: flex; justify-content: center;align-items: center; margin-top: 16px;">
                        <van-button block type="primary" size="small" style="width: 160px;" @click="onChange()">确定</van-button>
                    </div>
                </van-popup>
                
                <van-cell-group v-show="couponAmounShow">
                    <van-cell title="优惠金额" :value="couponAmount" />
                </van-cell-group>
                
                <div v-if="walletAmountVisible" style="margin-top: 16px;">
                    <van-cell title="钱包金额" :value="walletAmount" />
                </div>

                <div style="display: flex; justify-content: center;align-items: center; margin-top: 16px;">
                    <van-button 
                        block 
                        type="primary" 
                        size="small" 
                        style="width: 160px;" 
                        :disabled="!selectedChannel"
                        native-type="submit">
                        支付
                    </van-button>
                </div>
            </van-form>
        </div>
    </div>
</template>

<script setup>
import router from '@/router';
import { ref, onBeforeMount } from 'vue';
import { useRoute } from "vue-router";
import { showFailToast } from 'vant';
import { GetParList,GetPurseMoney,Payment} from '@/api/pay.js';
import { CouponAmount,UserCouponList} from '@/api/market.js';
const checked = ref([]);

//路由信息
const route = useRoute();
//返回按钮事件
const onClickLeft = () => history.back();
//支付渠道
var columns = ref({
    id:'',
    parname:'',

})
//面值
const fieldValue = ref('');
//支付方式选择显示
const showPicker = ref(false);

GetParList().then(res=>{
    console.log(res.data.data);
    columns.value=res.data.data
})


//优惠金额显示
const couponAmounShow = ref(false);
//优惠金额
var couponAmount = ref('0.00');
//显示优惠券列表
const showList = ref(false);
//选中的优惠券id
const selectedCouponIds = ref([]);
var selectedCount=ref('')



const amount = ref('');

var chargingRecordId = ref('11');

const pattern = /^(?![0-9]{1,2}\.0$)([1-9]\d*(?:\.\d{1,2})?)$/;
var payment=ref({
    amount:'',
    actualPrice: route.query.amount,
    userCouponIdList:'',
    chargeRecordId:'',
    vehicleIdentifyNo:route.query.vehicleIdentifyNo
})
function onSubmit() {
    payment.value.amount=couponAmount;
    payment.value.chargeRecordId= parseInt(route.query.id);
    payment.value.userCouponIdList=selectedCouponIds;
    Payment(payment.value)
    .then(res =>{
        if (res.data.code == 200000) {
            console.info(res.data.data)
            router.push({path: '/user/charge/pay/doing', query: { outTradeNo: res.data.data } })
        }else{
            showFailToast(res.data.message);
        }
    })
}

onBeforeMount(() => {
    console.log("根据chargingRecordId=" + route.query.id);
    chargingRecordId.value = route.query.id;
    console.log("根据amount=" + route.query.amount)
    amount.value = route.query.amount
    console.log("车架号:"+ route.query.vehicleIdentifyNo);
    
});

const id=route.query.id;
var queryM = ref({
    amount: parseFloat(route.query.amount),
    pageNum: 1,
    pageSize: 20,
    chargeStationInfoId:0,
    expireType: 0,
    status: 0
})

var userCouponInfList = ref([])
//获取当前用户可用优惠券
getUserCouponInf();
function getUserCouponInf() {
    userCouponInfList.value = [];
    queryM.value.expireType = 0;
    queryM.value.status=0;
    queryM.value.chargeStationInfoId=parseInt(id);

    UserCouponList(queryM.value)
        .then(res => {
            if (res.data.code == 200000) {
                console.log(res.data.data);
                
                userCouponInfList.value = res.data.data.records
            } else {
                //错误提示框
            }
        })
}

const queryCounponAmount=ref({
    selectedCouponIds:[],
    amount:''
})

//确认选择优惠券按钮
function onChange() {
    queryCounponAmount.value.amount=amount;
    queryCounponAmount.value.selectedCouponIds=selectedCouponIds.value;
    if(selectedCouponIds.value.length>0){
        selectedCount.value='已选择'+selectedCouponIds.value.length+'张'
    }else{
        selectedCount.value=''
    }
    
    CouponAmount(queryCounponAmount.value)
        .then(res => {
            console.info(res.data)
            if (res.data.code == 200000) {
                couponAmount.value = res.data.data
            } else {
                //错误提示框
                couponAmount.value=res.data.message
            }
        })
    showList.value = false;
    //调用后台计算出优惠总金额
    // couponAmount.value=100.99;
    couponAmounShow.value=true
}


function checkbox(couponId) {
    const selectedCoupon = userCouponInfList.value.find(coupon => coupon.id === couponId);
    
    if (selectedCoupon && selectedCoupon.coupon.overlay === 1) {
        // 如果选中的优惠券不可叠加，清空已选中的优惠券并只选中当前优惠券
        selectedCouponIds.value = [couponId];
    } else {
        const isInArray = selectedCouponIds.value.includes(couponId);
        if (isInArray) {
            selectedCouponIds.value = selectedCouponIds.value.filter(id => id !== couponId);
        } else {
            selectedCouponIds.value.push(couponId);
        }
    }
}

function showCouponList() {
    if (amount.value === '' || amount.value === undefined) {
        showFailToast('请先填写金额');
    } else {
        showList.value = true;
    }

}
 
// getChannelList()
// function getChannelList() {
//     ChannelsList()
//         .then(res => {
//             if (res.data.code == 200000) {
//                 columns.value = res.data.data
//             } else {
//                 //错误提示框
//             }
//         })
// }

const selectedChannel = ref(null);
const hoveredChannel = ref(null);

function selectChannel(channel) {
    fieldValue.value = channel.parname;
    selectedChannel.value = channel.id;
    console.log('选择的支付渠道:', channel);
}

const walletAmountVisible = ref(false);
const walletAmount = ref(0); // 钱包金额

function showWalletAmount(channel) {
    if (channel.parname === '钱包') {
         // 假设钱包的名称是 '钱包'

         GetPurseMoney().then(res=>{
            console.log(res.data.data);
         if(res.data.code==200000){
              walletAmount.value = res.data.data.balance; // 设置钱包金额
            walletAmountVisible.value = true; // 显示钱包金额
         }
        })

    } else {
        walletAmountVisible.value = false; // 隐藏钱包金额
    }
}

</script>
<style>
.van-cell__title {
    color: black;
}

.van-coupon-list {
    margin: var(--van-coupon-margin);
    background: var(--van-coupon-background);
    border-radius: var(--van-coupon-radius);
    box-shadow: var(--van-coupon-shadow);
    overflow: hidden;
}

.van-coupon-list-content {
    box-sizing: border-box;
    min-height: var(--van-coupon-content-height);
    padding: var(--van-coupon-content-padding);
    color: var(--van-coupon-content-text-color);
    align-items: center;
    display: flex;
    border-bottom: 1px solid black;
}

.van-coupon-list-head {
    min-width: var(--van-coupon-head-width);
    padding: 0 var(--van-padding-xs);
    color: var(--van-coupon-amount-color);
    text-align: center;
    position: relative;
}

.van-coupon-list-body {
    flex: 1;
    position: relative;
}

.van-coupon-amount {
    font-weight: var(--van-font-bold);
    font-size: var(--van-coupon-amount-font-size);
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-bottom: 6px;
    overflow: hidden;
}

.van-coupon-condition {
    font-size: var(--van-font-size-sm);
    white-space: pre-wrap;
    line-height: 16px;
}

.van-coupon-name {
    font-weight: var(--van-font-bold);
    font-size: var(--van-coupon-name-font-size);
    line-height: var(--van-line-height-md);
    margin-bottom: 10px;
}

.van-coupon-valid {
    font-size: var(--van-font-size-sm);
}

.van-coupon-checkbox {
    cursor: pointer;
    -webkit-user-select: none;
    user-select: none;
    align-items: center;
    display: none;
    overflow: hidden;
}
</style>